package cn.tedu.rtc.sdk.websocket.api;

import cn.tedu.rtc.sdk.websocket.ConcurrentWebSocketSession;
import cn.tedu.rtc.sdk.websocket.WebSocketMessageResponse;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.Collection;

public class WebSocketMessageSend {

    private static final Logger log = LoggerFactory.getLogger(WebSocketMessageSend.class);
    private static final JsonMapper.Builder MAPPER_BUILDER = JsonMapper.builder();

    public void sendMessage(ConcurrentWebSocketSession session, WebSocketMessageResponse message) {
        if (session == null) {
            return;
        }

        try {
            if (!session.isOpen()) {
                session.close();
                log.info("This session is closed.");
                return;
            }

            session.sendMessage(new TextMessage(MAPPER_BUILDER.build().writeValueAsBytes(message)));
        } catch (IOException e) {
            log.info("Failed to publish the message. {}", message.toString());
            String err = "The sending of webSocket message is abnormal.";
            log.info(String.format("Error Msg: %s. %s", err, e.getLocalizedMessage()));
            e.printStackTrace();
        }
    }

    public void sendBatch(Collection<ConcurrentWebSocketSession> sessions, WebSocketMessageResponse message) {
        if (sessions.isEmpty()) {
            return;
        }

        try {

            TextMessage data = new TextMessage(MAPPER_BUILDER.build().writeValueAsBytes(message));

            for (ConcurrentWebSocketSession session : sessions) {
                if (!session.isOpen()) {
                    session.close();
                    log.info("This session is closed.");
                    return;
                }
                session.sendMessage(data);
            }

        } catch (IOException e) {
            log.info("Failed to publish the message. {}", message.toString());
            String err = "The sending of webSocket message is abnormal.";
            log.info(String.format("Error Msg: %s. %s", err, e.getLocalizedMessage()));
            e.printStackTrace();
        }
    }
}